<template>
  <div class="AddChannelLink">
    <h5 v-if="state == 'edit'">编辑渠道链接</h5>
    <h5 v-else>新增渠道链接</h5>
    <div class="ele-title">
      <span>配置参数</span>
    </div>
    <div class="ele-form">
      <el-form ref="validate" :model="BindForm" :rules="pattern" label-position="left" label-width="140px">
        <el-form-item label="渠道链接名称:" prop="name">
          <el-col :span="5">
            <el-input
              v-model="BindForm.name"
              placeholder="输入名称"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="显示医院:" required>
          <el-col :span="24">
            <!--            <el-checkbox-group v-model="BindForm.hospitalIds">
              <el-checkbox v-for="item in hospitals" :key="item.id" :label="item.id">{{ item.hospitalName }}</el-checkbox>
            </el-checkbox-group>-->
            <HospitalGroup ref="hospitalList" :hospital-list="hospitals" />
          </el-col>
        </el-form-item>
        <el-form-item label="购物车:" prop="shoppingCart">
          <el-col :span="5">
            <el-radio-group v-model="BindForm.shoppingCart">
              <el-radio label="1">有</el-radio>
              <el-radio label="0">无</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="5">
            <el-alert
              title="选择是否显示购物车及加入购物车功能。"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="切换普通配送:" prop="normalDistribution">
          <el-col :span="5">
            <el-radio-group v-model="BindForm.normalDistribution">
              <el-radio label="1">允许</el-radio>
              <el-radio label="0">不允许</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="5">
            <el-alert
              title="选择是否允许选择普通配送地址，该限制为这个渠道的统一限制。与商品设置冲突时，以该限制为准"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="下单后跳转:" prop="orderRedirection">
          <el-col :span="5">
            <el-radio-group v-model="BindForm.orderRedirection">
              <el-radio label="0">围老首页</el-radio>
              <el-radio label="1">医院首页</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="显示商品:" prop="goodsShow">
          <el-col :span="5">
            <el-radio-group v-model="BindForm.goodsShow">
              <el-radio label="0">医院</el-radio>
              <el-radio label="1">护工或其他</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item v-if="!BindForm.carerId && BindForm.goodsShow == '1'" label="推广员">
          <el-col :span="24">
            <el-button type="text" @click="showDialog">添加推广员</el-button>
          </el-col>
        </el-form-item>
        <el-form-item v-if="BindForm.carerId" label="推广员">
          <el-col :span="24">
            <p>{{ BindForm.agent }}</p>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="24">
            <el-alert
              title="选择推广员之后，医院的商品也作为推广员的推广商品。如果存在商品冲突，则以医院的为准。"
              type="info"
              :closable="false"
            />
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-button
            style="width:200px;margin-left:100px"
            type="primary"
            @click="handelSubmit"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      :modal="false"
      :visible.sync="visible"
      title="选择推广员"
      @close="handelClose"
    >
      <el-form ref="storeForm" :model="storeForm">
        <div class="ele-key-search">
          <div class="left" />
          <div class="right">
            <el-input
              v-model="storeForm.keySearch"
              style="width:200px"
              maxlength="20"
              placeholder="输入手机号、名称搜索"
              suffix-icon="search"
            />
            <el-button type="primary" @click="handelSearch">确认</el-button>
          </div>
        </div>
      </el-form>
      <div class="ele-table">
        <el-table
          v-loading="loading"
          :data="BindataTuiGuangYuan"
          class="cus-table"
          height="550"
          :header-cell-style="handleCellStyle"
        >
          <el-table-column label="推广员" prop="nickname">
            <template slot-scope="scope">
              <span>{{ scope.row.nickname }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" prop="mobile" align="center" />
          <el-table-column label="操作" align="right">
            <template slot-scope="scope">
              <div class="operation">
                <el-button type="text" @click="selectAgent(scope.row)">选择</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="ele-footer">
        <div class="left" />
        <div class="right">
          <!--          <el-pagination
            :current-page="pages.pageIndex"
            :page-sizes="[10, 20, 30, 40, 50]"
            :page-size="pages.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pages.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />-->
          <!--          <el-pagination
            background
            :page-sizes="[10, 20, 30, 50, 100]"
            :page-size="pages.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pages.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />-->
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
/** 添加推广链接 */
import {
  addHospitalChannelLink,
  getMainAndOtherHospitalName,
  updateHospitalChannelLink
} from '@/api/customAPI/shop/hospitalManage'
import { ExtensionManagementList } from '@/api/customAPI/shop/ExtensionManagement'
import { Loading } from 'element-ui'
import HospitalGroup from '@/components/HospitalGroup'
export default {
  name: 'AddChannelLink',
  components: { HospitalGroup },
  data() {
    return {
      id: null,
      loading: false,
      state: '',
      BindForm: {
        /** 所属医院id	*/
        hospitalSendId: null,
        /** 渠道名称 */
        name: null,
        /** 显示医院id 逗号分隔 */
        hospitalIds: [],
        /** 是否显示购物车功能(0-否 1-是) */
        shoppingCart: '0',
        /** 切换普通配送 (0-不允许 1-允许) */
        normalDistribution: '0',
        /** 下单后跳转(0-围老首页 1-医院首页) */
        orderRedirection: '0',
        /** 显示商品（0-医院 1-护工） */
        goodsShow: '0',
        /** 护工id （显示商品为护工传） */
        carerId: null,
        /** 护工名称 */
        agent: null
      },
      storeForm: {
        keySearch: null
      },
      agentList: [],
      hospitals: [],
      visible: false,
      /** 推广员列表 */
      BindataTuiGuangYuan: [],
      pages: {
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      pattern: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        /* hospitalIds: [{ required: true, message: '请勾选医院', trigger: 'change' }],*/
        shoppingCart: [
          {
            required: true,
            message: '请勾选购物车',
            trigger: 'change'
          }
        ],
        normalDistribution: [
          {
            required: true,
            message: '请勾选切换普通配送',
            trigger: 'change'
          }
        ],
        orderRedirection: [{ required: true, message: '请选择下单后跳转', trigger: 'change' }],
        goodsShow: [
          { required: true, message: '请勾选显示商品', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    BindForm: {
      goodsShow: {
        handle(newValue, oldValue) {
          if (this.BindForm.goodsShow == '0') {
            this.BindForm.carerId = null
          }
        },
        deep: true
      }
    }
  },
  created() {
    const params = this.$dd(this.$route.query.p)
    if (params.edit) {
      this.state = 'edit'
      this.id = params.channelLink.id
    } else {
      this.state = 'add'
    }
    this.loadding()
  },
  mounted() {
    const params = this.$dd(this.$route.query.p)
    if (params.edit) {
      this.getInfo()
    }
  },
  methods: {
    /** 编辑加载数据*/
    getInfo() {
      const params = this.$dd(this.$route.query.p)
      this.BindForm.name = params.channelLink.channelName
      this.$nextTick(() => {
        params.channelLink.hospitalIds.split(',').forEach(item => {
          this.BindForm.hospitalIds.push(parseInt(item))
        })
        this.$refs.hospitalList.setData(this.BindForm.hospitalIds)
        console.log(this.$refs.hospitalList.getData())
      })

      this.BindForm.shoppingCart = params.channelLink.shoppingCart.toString()
      this.BindForm.normalDistribution = params.channelLink.normalDistribution.toString()
      this.BindForm.orderRedirection = params.channelLink.orderRedirection.toString()
      this.BindForm.goodsShow = params.channelLink.goodsShow.toString()
      if (params.channelLink.carerId) {
        this.BindForm.carerId = params.channelLink.carerId
        this.BindForm.agent = params.channelLink.carerName
      }
      console.log(this.BindForm)
    },
    /** 初始化加载*/
    loadding() {
      const params = this.$dd(this.$route.query.p)
      console.log(params)
      this.BindForm.hospitalSendId = params.hospitalId
      getMainAndOtherHospitalName(this.BindForm.hospitalSendId).then(res => {
        this.hospitals = res.data.data
        console.log(this.hospitals)
      }).catch(err => {
        console.log(err)
      })
      this.loadTableData()
    },
    showDialog() {
      this.visible = true
      this.loadTableData()
    },
    /** 头部行颜色 */
    handleCellStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background:#f3f3f3'
      } else {
        return ''
      }
    },
    /** 刷新 */
    resetForm() {
      const vm = this
      vm.storeForm.keySearch = null
      vm.reloadTableData()
    },
    reloadTableData() {
      const vm = this
      vm.pages.pageIndex = 1
      vm.pages.total = 0
      vm.BindataTuiGuangYuan = []
      vm.loadTableData()
    },
    loadTableData() {
      const data = {
        shopId: localStorage.getItem('shopId'),
        page: this.pages.pageIndex,
        limit: this.pages.pageSize
      }
      if (this.storeForm.keySearch) {
        data['keySearch'] = this.storeForm.keySearch
      }
      ExtensionManagementList(data).then(res => {
        this.BindataTuiGuangYuan = res.data.data
        this.pages.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    },
    /**  显示条目
     *  @param size 一页显示的条目
     */
    handleSizeChange(size) {
      this.pages.pageSize = size
      this.loadTableData()
    },
    /**  当前页
     *  @param index 显示页
     */
    handleCurrentChange(index) {
      this.pages.pageIndex = index
      this.loadTableData()
    },
    /** 关闭弹出框*/
    handelClose() {
      this.visible = false
    },
    /** 搜索*/
    handelSearch() {
      this.reloadTableData()
    },
    /** 选择推广员*/
    selectAgent(row) {
      this.BindForm.agent = row.nickname
      this.BindForm.carerId = row.agentId
      this.visible = false
    },
    /** 提交 */
    handelSubmit() {
      this.$refs.validate.validate(v => {
        if (v) {
          this.$nextTick(() => {
            console.log(this.$refs.hospitalList.getData())
            if (this.$refs.hospitalList.getData().length < 0) {
              return this.$message.error('至少选择一个医院')
            } else {
              const hospitals = this.$refs.hospitalList.getData().toString()
              console.log(hospitals)
              const data = {
                hospitalSendId: this.BindForm.hospitalSendId,
                name: this.BindForm.name,
                hospitalIds: hospitals,
                shoppingCart: this.BindForm.shoppingCart,
                normalDistribution: this.BindForm.normalDistribution,
                orderRedirection: this.BindForm.orderRedirection,
                goodsShow: this.BindForm.goodsShow
              }
              if (this.BindForm.goodsShow == '1') {
                if (!this.BindForm.carerId) {
                  return this.$message.error('请选择推广员')
                } else {
                  data['carerId'] = this.BindForm.carerId
                }
              }
              if (this.state == 'edit') {
                data['id'] = this.id
                const loadingInstance = Loading.service({ fullscreen: true })
                updateHospitalChannelLink(data).then(res => {
                  loadingInstance.close()
                  this.$message.success('编辑渠道链接成功')
                  this.$store.dispatch('tagsView/delView', this.$route)
                  this.$router.go(-1)
                }).catch(err => {
                  console.log(err)
                  loadingInstance.close()
                })
              } else {
                const loadingInstance = Loading.service({ fullscreen: true })
                addHospitalChannelLink(data).then(res => {
                  loadingInstance.close()
                  this.$message.success('新增渠道链接成功')
                  this.$store.dispatch('tagsView/delView', this.$route)
                  this.$router.go(-1)
                }).catch(err => {
                  console.log(err)
                  loadingInstance.close()
                })
              }
            }
          })
        }
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.AddChannelLink {
  padding: 50px 100px;
  .ele-title {
    height: 50px;
    line-height: 50px;
    background: #f3f3f3;
    border-radius: 5px;
    padding-left: 20px;
  }
  .ele-form {
    margin-top: 30px;
    ::v-deep.el-form {
      .el-form-item__label {
        width: 100px;
        text-align: start;
      }
      /*.el-form-item__error {
        margin-left: 0;
      }*/
    }
  }
  .ele-key-search {
    display: flex;
    justify-content: space-between;
    margin-bottom: 22px;
  }
  .ele-footer {
    display: flex;
    justify-content: space-between;
  }
}
</style>
